package com.example.template.core.utils;
/**
 * Description: //TODO
 * Created by meko on 19-3-17上午11:40
 */


import com.example.template.core.entity.BaseEntity;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

/**
 *@Description TODO
 *@Author create by meko at 19-3-17 上午11:40
 **/
public class FilterUtil {


    /**
     * @Description //TODO
     * @Date 19-3-17 上午11:51
     * @Param [entity, keywords, orderBy]
     * @Param keywords  模糊查询关键词: 字段名_内容 >>> name_%mee%
     * @Param dataScope 查询的范围: 自段类型_字段名_开始范围_结束范围 >>> date_createTime_2019-03-04_2019-04-10
     * @Param orderBy 排序方式: 字段名_升降序 >>> age_DESC
     * @return tk.mybatis.mapper.entity.Example
     **/
    public static Example parsePropertyFilterExp(BaseEntity entity, String keywords, String orderBy, String dataScope)throws Exception{
        String string = "string";
        String date = "date";
        String integer = "int";
        Example example = new Example(entity.getClass());
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(entity);
        if (dataScope != null && dataScope.contains("_")){
            String[] strings = dataScope.split("_");
//            按字符串类型范围查询
            if (string.equals(strings[0].trim())){
                criteria.andBetween(strings[1].trim(),strings[2].trim(),strings[3].trim());
                //按时间范围查询
            }else if (date.equals(strings[0].trim())){
                Date startBeginDate = DateUtil.birthdayFormat(strings[2]);
                Date endBeginDate = DateUtil.birthdayFormat(strings[3]);
                criteria.andBetween(strings[1].trim(),startBeginDate,endBeginDate);
                //按数字范围查询
            }else if(integer.equals(strings[0].trim())){
                criteria.andBetween(strings[1].trim(),Integer.parseInt(strings[2].trim()),Integer.parseInt(strings[3].trim()));
            }
        }
        if (keywords != null && keywords.contains("_")){
            String[] strings = keywords.split("_");
            criteria.andLike(strings[0],strings[1]);
        }
        if (orderBy != null && orderBy.contains("_")){
            String[] strings = orderBy.split("_");
            if ("".equals(strings[1].trim()) || "ASC".equals(strings[1].toUpperCase().trim())){
                example.orderBy(strings[0].trim()).asc();
            }else {
                example.orderBy(strings[0].trim()).desc();
            }
        }

        return example;
    }


}
